import React, { forwardRef, useState, useImperativeHandle, ChangeEvent, useRef } from 'react';
import { Modal, Upload, Form, UploadProps, Progress } from 'antd';
import { InboxOutlined, PayCircleOutlined, BankOutlined, DesktopOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import type { TabsProps } from 'antd';
import { commonErrorMsg, deepCopy, getChangeEventValue, isEmpty, toastShort } from '../../../utils';
import Link from 'antd/es/typography/Link';
import { RcFile } from 'antd/es/upload';
import axios from 'axios';
import { useSearchParams } from 'react-router-dom';
import { saasConfig } from '../../../config/theme-config';

interface Props {
    onFinish?: Function
}


const { Dragger } = Upload;

const UploadShareFileModal = (props: Props, ref: any) => {
    useImperativeHandle(ref, () => ({
        openModal: openModal
    }))

    const {
        onFinish
    } = props;

    const [searchParams, setSearchParams] = useSearchParams();

    const [submitLoading, setSubmitLoading] = useState(false);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [form] = Form.useForm<{ name?: string }>();
    const [formData, setFormData] = useState<{ name?: string }>({});

    const [uploadProgress, setUploadProgress] = useState<number>(0);
    const [fileList, setFileList] = useState([]);

    const uploadFile = async (_formdata) => {
        return new Promise((resolve, reject) => {
            const xhr = new XMLHttpRequest();

            xhr.upload.addEventListener('progress', (event) => {
                if (event.lengthComputable) {
                    const progress = (event.loaded / event.total) * 100;
                    let _uploadProgress = Number(progress.toFixed(2));
                    // console.log(`上传进度：${progress.toFixed(2)}%`);
                    setUploadProgress(_uploadProgress);
                }
            });

            xhr.onreadystatechange = () => {
                if (xhr.readyState === 4) {
                    if (xhr.status >= 200 && xhr.status < 300) {
                        resolve(JSON.parse(xhr.responseText));
                    } else {
                        reject(new Error('上传失败'));
                    }
                }
            };
            xhr.open('POST', `${saasConfig.nodeJsApiBaseUrl + saasConfig.matchPath}/shared_folder/create_share_file`, true);
            xhr.setRequestHeader('Authorization', `Bearer ${localStorage.getItem('token')}`);
            xhr.send(_formdata);
        });
    };

    const encode = (str) => {
        // 对字符串进行编码
        var encode = encodeURI(str);
        // 对编码的字符串转化base64
        var base64 = btoa(encode);
        return base64;
    }

    const handleConfirm = () => {
        const _formdata = new FormData();
        fileList.forEach((file) => {
            const originalFilename = file.name;
            const base64Filename = encode(originalFilename);
            const blob = file.slice(0, file.size, file.type);
            const fileWithBase64Name = new File([blob], base64Filename, {
                type: file.type,
                lastModified: file.lastModified,
            });
            _formdata.append('files', fileWithBase64Name);
        });
        const parentFolderId = searchParams.get('pfid');
        if(!isEmpty(parentFolderId)){
            _formdata.append('parentFolderId', parentFolderId)
        }
        setSubmitLoading(true);
        uploadFile(_formdata)
            .then(res => {
                setSubmitLoading(false)
                console.log("测试结果", res)
                setIsModalOpen(false);
                onFinish && onFinish();
            })
            .catch(err => {
                setSubmitLoading(false)
                toastShort('error', commonErrorMsg)
            })
    };

    const openModal = () => {
        const { keys, values } = Object;
        setUploadProgress(0);
        setFileList([]);
        setIsModalOpen(true);
    };

    const handleCancel = () => {
        setIsModalOpen(false);
    };

    const handleSetFormData = (target: string, value: any) => {
        let _formData = formData;
        //@ts-ignore
        _formData[target] = value;
        setFormData(deepCopy(_formData));
    };

    const uploadProps: UploadProps = {
        name: 'file',
        multiple: false,
        accept: ".xlx,.xlsx,.doc,.docx,.ppt,.pptx,.jpg,.png,.jpeg,.zip,.rar,.pdf",
        beforeUpload: (file) => {
            // console.log('beforeUpload--->', file)
            let newFileList = [...fileList, file];
            if(newFileList.length > 5){
                toastShort('warning', '文件上传数量超出限制')
            }else {
                setFileList(newFileList);
            }
            return false;
        },
        maxCount: 5,
        fileList: fileList,
        onChange(info) {
            const { status } = info.file;
            if (status !== 'uploading') {
                console.log(info.file, info.fileList);
            }
            if (status === 'done') {
                toastShort('success', `${info.file.name} file uploaded successfully.`);
            } else if (status === 'error') {
                toastShort('error', `${info.file.name} file upload failed.`);
            }
        },
        onRemove(e){
            let _fileList = fileList;
            for(let i = 0; i < _fileList.length; i ++){
                if(_fileList[i].uid == e.uid){
                    _fileList.splice(i, 1);
                    break;
                }
            }
            setFileList([..._fileList])
        },
        onDrop(e) {
            console.log('Dropped files', e.dataTransfer.files);
        },
    };

    return (
        <Modal
            title={'共享文件上传'}
            open={isModalOpen}
            onOk={handleConfirm}
            onCancel={handleCancel}
            okText={'确 认'}
            cancelText={'取 消'}
            width={612}
            maskClosable={false}
            confirmLoading={submitLoading}
            centered
        >
            <div className='custom-modal-container'>
                <Form
                    size={'large'}
                    form={form}
                    layout={'horizontal'}
                    autoComplete="off"
                    labelAlign={'right'}
                    labelCol={{ span: 4 }}
                    style={{ width: '100%' }}
                >
                    <Form.Item
                        label="文件上传"
                        name={'name'}
                        required
                    >
                        <Dragger
                            {...uploadProps}
                            disabled={fileList.length >= 5}
                        >
                            <p className="ant-upload-drag-icon">
                                <InboxOutlined />
                            </p>
                            <p className="ant-upload-text">点击或拖拽文件到此处</p>
                            <p className="ant-upload-hint">
                                支持xlx、xlsx、doc、docx、ppt、pptx、jpg、png、
                            </p>
                            <p className="ant-upload-hint">
                                jpeg、zip、rar、pdf格式的文件(单文件最大不超过25M)
                            </p>
                        </Dragger>
                        <div style={{ width: '100%', paddingLeft: 0, paddingRight: 0, paddingTop: 12 }}>
                            <Progress percent={uploadProgress} />
                        </div>
                    </Form.Item>
                </Form>
            </div>
        </Modal>
    )
}


export default forwardRef(UploadShareFileModal)